package com.jwater.gateway.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 默认是DefaultErrorWebExceptionHandler错误处理，这里替换掉了默认的错误处理handler，
 * 这里写得比较简单，如果不满足要求，参考DefaultErrorWebExceptionHandler增加逻辑
 *
 * @author jnner
 */
@Order(-1)
@Component
public class CommonExceptionHandler implements ErrorWebExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        if (ex instanceof ResponseStatusException) {
            response.setStatusCode(((ResponseStatusException) ex).getStatus());
        }

        if (ex.getClass().getSimpleName().equals("AnnotatedConnectException")) {
            LOGGER.error(ex.toString());
        } else {
            LOGGER.error(ex.toString(), ex);
        }
        return writeResponse(exchange, ex);
    }

    private Mono<Void> writeResponse(ServerWebExchange exchange, Throwable ex) {
        try {
            exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
            DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(ex.toString().getBytes());
            return exchange.getResponse().writeWith(Flux.just(dataBuffer));
        } catch (Exception e) {
            LOGGER.error(e.toString(), e);
        }
        return exchange.getResponse().setComplete();
    }
}
